package com.fg.cloud.manager.service.system.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.Result;
import com.fg.cloud.common.ServiceException;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.finals.FlowStatus;
import com.fg.cloud.manager.entry.factory.FactoryProcessEntity;
import com.fg.cloud.manager.entry.factory.vo.FactoryProcessVo;
import com.fg.cloud.manager.entry.order.OrderCheckEntity;
import com.fg.cloud.manager.entry.order.OrderDetailEntity;
import com.fg.cloud.manager.entry.order.OrderInfoEntity;
import com.fg.cloud.manager.mapper.agency.AgencyMapper;
import com.fg.cloud.manager.mapper.factory.FactoryProcessMapper;
import com.fg.cloud.manager.mapper.order.OrderCheckMapper;
import com.fg.cloud.manager.mapper.order.OrderDetailMapper;
import com.fg.cloud.manager.mapper.order.OrderInfoMapper;
import com.fg.cloud.manager.mapper.system.SystemOrderMapper;
import com.fg.cloud.manager.service.order.OrderCheckService;
import com.fg.cloud.manager.service.order.OrderDetailService;
import com.fg.cloud.manager.service.order.OrderInfoService;
import com.fg.cloud.manager.service.system.SystemOrderService;

@Service
public class SystemOrderServiceImpl implements SystemOrderService{

	@Autowired
	private SystemOrderMapper SystemOrderMapper;
	@Autowired
	private OrderInfoService agency_orderService;
	@Autowired
	private OrderDetailService detailService ;
	@Autowired
	private OrderCheckService checkService ;
	@Autowired
	private FactoryProcessMapper processMapper ;
	@Autowired
	private OrderInfoMapper orderMapper ;
	@Autowired
	private OrderDetailMapper detailMapper ;
	@Autowired
	private OrderCheckMapper checkMapper ; 
	
	@Override
	public void findBySenior(PageUtils<OrderInfoEntity> pageinfo) {
		Long count = SystemOrderMapper.findBySeniorCount(pageinfo);
		pageinfo.setTotal(count);
		if(count == 0){
			pageinfo.setData(new ArrayList<OrderInfoEntity>());
		}
		pageinfo.setData(SystemOrderMapper.findBySenior(pageinfo));
	}

	@Override
	@Transactional
	public Long delete(List<Long> id) {
		// 订单删除,包括订单头,订单详情,日志
		SystemOrderMapper.deleteLog(id);
		SystemOrderMapper.deleteDetail(id);
		return SystemOrderMapper.deleteinfo(id);
	}

	@Override
	public OrderInfoEntity findOrderDetail(Long id, Long facId) {
		OrderInfoEntity order = agency_orderService.find(id);
		if(order == null ){
			return null;
		}
		List<OrderDetailEntity> detail = detailService.selectByOrderId(id,"desc","id");
		List<OrderCheckEntity> operatorRecord = checkService.selectByOrderId(id);
		if(detail == null || detail.size() < 0){
			return null;
		}
		List<FactoryProcessVo> processList = new ArrayList<FactoryProcessVo>();
		processList = getOrderProcess(order, facId);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");   
		order.setDeliveryDateStr(sdf.format(order.getDeliveryDate()));
		order.setProcessList(processList);
		//order.setRows(detail);
		order.setOperatorRecords(operatorRecord);
		return order;
	}

	/**
	 * Description:获取订单的整个流程信息
	 * @param order 订单信息
	 * @param facId 厂商信息
	 * @return List<FactoryProcessVo>
	 * @author liushengchao
	 * @date  2017年9月26日下午7:19:20
	 */
	public List<FactoryProcessVo> getOrderProcess(OrderInfoEntity order ,Long facId){
		FactoryProcessEntity processEntity = processMapper.selectByfacId(facId);
		List<FactoryProcessVo> processList = new ArrayList<>();
		int orderStatus = order.getOrderStatus();
		FactoryProcessVo process0 = new FactoryProcessVo();
		process0.setProcessName("开始");
		process0.setProcessStatus(true);
		processList.add(process0);
		FactoryProcessVo process1 = new FactoryProcessVo();
		process1.setProcessName("业务审核");
		process1.setProcessStatus(false);
		processList.add(process1);
		FactoryProcessVo process2 = new FactoryProcessVo();
		if(orderStatus == 10 ){
			if(orderStatus == 1){
				process1.setProcessName("业务审核");
				process1.setProcessStatus(true);
				processList.add(process1);
			}
			process2.setProcessName("订单作废");
			process2.setProcessStatus(true);
			processList.add(process2);
			return processList ;
		}
		FactoryProcessVo process3 = new FactoryProcessVo();
		process3.setProcessName("财务审核");
		process3.setProcessStatus(false);
		FactoryProcessVo process4 = new FactoryProcessVo();
		process4.setProcessName("发货（部分发货）");
		process4.setProcessStatus(false);
		FactoryProcessVo process6 = new FactoryProcessVo();
		process6.setProcessName("已收货");
		process6.setProcessStatus(false);
		if(orderStatus >= 1){
			process1.setProcessName("业务审核");
			process1.setProcessStatus(true);
		}
		if(orderStatus >=2 && !StringUtils.isEmpty(process3.getProcessName())&&
				processEntity.getFinanceReview() == 0){
			process3.setProcessName("财务审核");
			process3.setProcessStatus(true);
		}
		if(orderStatus >= 3 && !StringUtils.isEmpty(process4.getProcessName())
				&&processEntity.getShipConfirm() == 0){
			process4.setProcessName("发货（部分发货）");
			process4.setProcessStatus(true);
		}
		if(orderStatus >= 5 && !StringUtils.isEmpty(process6.getProcessName())
				&&processEntity.getReceivingConfirm() ==0){
			process6.setProcessName("已收货");
			process6.setProcessStatus(true);
		}
		FactoryProcessVo process7 = new FactoryProcessVo();
		if(orderStatus == 6){
			process7.setProcessName("完成");
			process7.setProcessStatus(true);
		}else{
			process7.setProcessName("完成");
			process7.setProcessStatus(false);
		}
		processList.add(process3);
		processList.add(process4);
		processList.add(process6);
		processList.add(process7);
		return processList;
	}

	@Override
	public List<OrderDetailEntity> orderDetailList(Long id, Long facId) {
		List<OrderDetailEntity> detail = detailService.selectByOrderId(id,"desc","id");
		return detail;
	}

	/**
	 * 详情删除
	 * */
	@Override
	public Result deleteDetail(Long id) {
		SystemOrderMapper.deleteOneDetail(id);
		return Result.result(null, true, StatusCode.REMOVESUCCESS, "删除成功");
	}
	/**
	 * 修改订单
	 * */
	@Override
	@Transactional
	public Result modifyOrder(OrderInfoEntity order) throws ServiceException {
		BigDecimal amountTotal = new BigDecimal(0) ;
		if(order == null || StringUtils.isEmpty(order.getOrderNo()) || order.getFacId() == null || order.getAgeId() == null ){
			throw new ServiceException(StatusCode.LACKVALUE,"订单信息、订单编号、经销商和订单商品不能为空");
		}
		/*if(null == order.getRows() || 0 == order.getRows().size()){
			throw new ServiceException(StatusCode.LACKVALUE,"订单商品不能为空");
		}
		AgencyVo agencyVo = agencyMapper.selectAgencyInfo(order.getAgeId(),order.getFacId());
		for(OrderDetailEntity detail : order.getRows()){
			if(detail.getSkuId() == null || detail.getProductId() == null ||detail.getProductId() <0  
					|| StringUtils.isEmpty(detail.getProductName())  
					|| StringUtils.isEmpty(detail.getProductNumber())){
				throw new ServiceException(StatusCode.LACKVALUE,"订单商品、商品名称和商品编码不能为空");
			}
		}*/
		int flag = 0 ;
		/*for(OrderDetailEntity detail : order.getRows()){
			BigDecimal discount = agencyVo.getDiscount(); 
			detail.setPromotionPrice(detail.getSellPrice().multiply(discount).divide(new BigDecimal(100)));
			detail.setSumMoney(detail.getPromotionPrice().multiply(detail.getAmount()));
			amountTotal = amountTotal.add(detail.getSumMoney());
			flag = detailMapper.update(detail);
			if(flag < 0){
				throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序异常");
			}
		}*/
		order.setAmountTotal(amountTotal);
		order.setAmountPay(amountTotal.add(order.getExpressFee()));
		//order.setDeliveryDate(DateUtil.stringToDate(order.getDeliveryDateStr(), DateUtil.DATE_TO_STRING_SHORT_PATTERN));
		order.setUpdater(Long.valueOf(0));//  管理员,直接给0了
		order.setUpdateTime(new Date());
		flag = orderMapper.update(order);
		if(flag < 0){
			throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序异常");
		}
		OrderCheckEntity checkEntity = setCheckData(order.getId(),FlowStatus.MODIFY,order.getOrderNo(),order.getFacId()) ;
		checkMapper.insert(checkEntity);
		return Result.result(null, true, StatusCode.SAVESUCCESS, "修改成功");
	}
	
	/**
	 * Description:给流程节点实体赋值
	 * @param orderId 订单ID
	 * @param checkName 流程节点名称
	 * @return
	 * @author liushengchao
	 * @date  2017年9月5日上午9:09:37
	 */
	public OrderCheckEntity setCheckData(Long orderId,String checkName,String orderNo,Long facId){
		OrderCheckEntity checkEntity = new OrderCheckEntity() ;
		checkEntity.setOrderId(orderId);
		checkEntity.setFacId(facId);
		checkEntity.setCheckUserId(Long.valueOf(0));
		checkEntity.setCheckUser("超级管理员");
		checkEntity.setCheckName(checkName);
		checkEntity.setCheckDate(new Date());
		return checkEntity ;
	}

	@Override
	public Result modifyOrderDetail(OrderDetailEntity detail) {
		Integer a = detailMapper.update(detail);
		return Result.result(null, true, StatusCode.SAVESUCCESS, "修改成功");
	}
}
